package com.linkoog.devtools.dubbo.invoke;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public interface DubboInvoker {

    String invoke(DubboRequest dubboRequest);


    default boolean compareMethodType(String[] reqParamTypes,  List<String> paramTypes){
        if (reqParamTypes.length != paramTypes.size()) return false;


        for (int i = 0; i < reqParamTypes.length; i++) {
            String reqParamType = reqParamTypes[i];
            String paramType = paramTypes.get(i);

            //TODO: 数组类型处理
            if (!(reqParamType.equals(paramType) || reqParamType.endsWith(paramType))){
                return false;
            }
        }


        return true;
    }


    default SelectMethod parseSelectMethod(String line){
        if (StringUtils.isBlank(line)) return null;

        // 定义正则表达式模式
        String pattern = "^(\\d+)\\.\\s*(\\w+)\\(([^)]*)\\)$";
        Pattern regexPattern = Pattern.compile(pattern);
        Matcher matcher = regexPattern.matcher(line);

        // 进行匹配
        if (matcher.find()) {
            String number = matcher.group(1);
            String methodName = matcher.group(2);
            String parameterTypesStr = matcher.group(3);

            List<String> parameterTypes = parseParameterTypes(parameterTypesStr);
            return new SelectMethod(number, methodName, parameterTypes);
        }

        return null;
    }

    default List<String> parseParameterTypes(String parameterTypesStr) {
        List<String> parameterTypes = new ArrayList<>();
        String[] types = parameterTypesStr.split(",");
        for (String type : types) {
            parameterTypes.add(type.trim());
        }
        return parameterTypes;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class SelectMethod {
        private String number;
        private String methodName;
        private List<String> parameterTypes;
    }


}
